package leetcode.D100.T19;

import util.ListNode;

/**
 * @File Info: leetcode -- <Solution>
 * @Author: DYZ
 * @Create: 2021-08-09 14:34:27 星期一
 */

public class Solution {
    // 一刷
    /*public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode pre = head, p = head, q = new ListNode(0, head);
        head = q;
        for(int i=0; i<n; ++i) {
            pre = pre.next;
        }
        while(pre != null) {
            pre = pre.next;
            q = p;
            p = p.next;
        }
        q.next = p.next;
        return head.next;
    }*/

    // 二刷
    /*public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode q = new ListNode(0, head);
        head = q;
        ListNode pre = head;
        for (int i = 0; i < n+1; i++) {
            q = q.next;
        }
        while(q != null) {
            q = q.next;
            pre = pre.next;
        }
        pre.next = pre.next.next;
        return head.next;
    }*/

    // 三刷
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head), pre = dummy, p = pre.next;
        for (int i=0; i<n; ++i)
            p = p.next;
        while (p != null) {
            p = p.next;
            pre = pre.next;
        }
        pre.next = pre.next.next;
        return dummy.next;
    }
}
